package com.weixing.mall.provider.support.mq;

import com.weixing.mall.provider.service.IActivityGoodsService;
import com.weixing.mall.redis.RedisKeyConst;
import com.weixing.mall.redis.order.OrderPayEnd;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Order(1)
public class OrderPayEndRedissionQueueConsumer implements CommandLineRunner {

    private RedissonClient redissonClient;

    @Autowired
    private IActivityGoodsService activityGoodsService;

    @Resource
    private TaskExecutor taskExecutor;

    @Autowired
    public OrderPayEndRedissionQueueConsumer(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    private void consumerOfOrderPayEnd() {
        taskExecutor.execute(() -> this.orderPayEnd());
    }


    private void orderPayEnd() {
        RBlockingQueue<OrderPayEnd> blockingFairQueue = redissonClient.getBlockingQueue(RedisKeyConst.QUEUE_ORDER_PAY_END);
        RDelayedQueue<OrderPayEnd> delayedQueue = redissonClient.getDelayedQueue(blockingFairQueue);
        while (true) {
            OrderPayEnd payEnd = null;
            try {
                payEnd = blockingFairQueue.take();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            activityGoodsService.cancelOrder(payEnd);
//            System.out.println("订单：" + payEnd.getOrderId() + "::" + payEnd.getItemId() + "::" + payEnd.getPutTime());

        }
    }


    @Override
    public void run(String... args) throws Exception {
        System.out.println("启动第一个任务");
        consumerOfOrderPayEnd();
    }
}